<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="订单ID" prop="customerOrderId">-->
<!--        <el-input v-model="queryParams.customerOrderId" placeholder="请输入订单ID" clearable @keyup.enter="handleQuery"/>-->
<!--      </el-form-item>-->
      <el-form-item label="订单编号" prop="orderCode">
        <el-input v-model="queryParams.orderCode" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="不良日" prop="defectDate">
        <el-date-picker clearable v-model="queryParams.defectDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择不良日">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status" style="width: 264.4px">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in scm_defect_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="Plus"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['scm:scmDefectInfo:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="Edit"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['scm:scmDefectInfo:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="Delete"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['scm:scmDefectInfo:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="Download"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['scm:scmDefectInfo:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :search="false" :columns="columns" showColumnsType="transfer" ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scmDefectInfoList" @selection-change="handleSelectionChange" :scrollbar-always-on="true" >
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="图号" align="center" prop="projectProduct.drawingNumber" fixed width="98"/>
      <el-table-column label="版本" align="center" prop="projectProduct.version" fixed v-if="columns[0].visible" />
      <el-table-column label="内版本" align="center" prop="projectProduct.internalVersion" fixed v-if="columns[1].visible" />
      <el-table-column label="品名" align="center" prop="projectProduct.productName" fixed v-if="columns[2].visible" />
<!--      <el-table-column label="ID" align="center" prop="id" />-->
<!--      <el-table-column label="项目id" align="center" prop="projectId" />-->
<!--      <el-table-column label="产品id" align="center" prop="productId" />-->
<!--      <el-table-column label="项目产品ID" align="center" prop="projectProductId" />-->
<!--      <el-table-column label="订单ID" align="center" prop="customerOrderId" />-->
      <el-table-column label="订单编号" align="center" prop="orderCode" />
      <el-table-column label="不良日" align="center" prop="defectDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.defectDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="scm_defect_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="检查数量" align="center" prop="inspectionCount" />
      <el-table-column label="不良数量" align="center" prop="defectCount" />
      <el-table-column label="不良率(%)" align="center" prop="defectRate" />
      <el-table-column label="不良类型" align="center" prop="defectType" />
      <el-table-column label="不良内容" align="center" prop="defectDetails" />
      <el-table-column label="原因分析" align="center" prop="reasonAnalysis" />
      <el-table-column label="RD对策" align="center" prop="countermeasure" />
      <el-table-column label="返品时间" align="center" prop="toCustReturnDate" width="98">
        <template #default="scope">
          <span>{{ parseTime(scope.row.toCustReturnDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="返品数量对应的时间" align="center" prop="returnQuantityTime" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.returnQuantityTime, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="返品数量" align="center" prop="returnQuantity" />-->
      <el-table-column label="出货时间" align="center" prop="shipmentQuantityTime" width="98">
        <template #default="scope">
          <span>{{ parseTime(scope.row.shipmentQuantityTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出货数量" align="center" prop="shipmentQuantity" />
      <el-table-column label="未代品数" align="center" prop="unsubstitutedQuantity" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['scm:scmDefectInfo:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['scm:scmDefectInfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改不良品信息记录对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="scmDefectInfoRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="图号" prop="projectProductsId" style="width: 264.4px" >
              <el-select
                  v-model="form.projectProductId" filterable remote reserve-keyword placeholder="请输入项目中的图号"
                  :remote-method="remoteMethodOfProjectProducts" @change="handleChangeOfProjectProducts" :loading="loading" >
                <el-option
                    v-for="item in optionsOfProduct" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="品名" prop="projectProduct.productName" >
              <el-input v-model="form.projectProduct.productName" placeholder="" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="版本号" prop="projectProduct.productName">
              <el-input v-model="form.projectProduct.version" placeholder="" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="内版本号" prop="projectProduct.productName">
              <el-input v-model="form.projectProduct.internalVersion" placeholder="" disabled />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="订单编号" prop="customerOrderId">
              <el-select v-model="form.customerOrderId" filterable remote reserve-keyword placeholder="请输入订单编号"
                         :remote-method="remoteMethodOfCustomerOrders" @change="handleChangeOfCustomerOrders" :loading="loading" >
                <el-option
                    v-for="item in optionsOfCustomerOrders" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="6">-->
<!--            <el-form-item label="订单编号" prop="orderCode">-->
<!--              <el-input v-model="form.orderCode" placeholder="请输入订单编号" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="6">
            <el-form-item label="不良日" prop="defectDate">
              <el-date-picker clearable
                              v-model="form.defectDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择不良发生日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态|0:-,1:待处理,2:处理中,3:处理完成,4:处理失败">
                <el-option
                    v-for="dict in scm_defect_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="检查数量" prop="inspectionCount">
              <el-input v-model="form.inspectionCount" placeholder="请输入检查数量" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="不良数量" prop="defectCount">
              <el-input v-model="form.defectCount" placeholder="请输入不良数量" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="不良率(%)" prop="defectRate">
              <el-input v-model="form.defectRate" placeholder="请输入不良率(%)" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="不良类型" prop="defectType">
              <el-input v-model="form.defectType" placeholder="请输入不良类型" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="不良内容" prop="defectDetails">
              <el-input v-model="form.defectDetails" placeholder="请输入不良内容描述" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="原因分析" prop="reasonAnalysis">
              <el-input v-model="form.reasonAnalysis" placeholder="请输入RD原因分析" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="RD对策" prop="countermeasure">
              <el-input v-model="form.countermeasure" placeholder="请输入RD对策" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="返品时间" prop="toCustReturnDate">
              <el-date-picker clearable
                              v-model="form.toCustReturnDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择RD到HP的返品时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出货时间" prop="shipmentQuantityTime">
              <el-date-picker clearable
                              v-model="form.shipmentQuantityTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择出货数量对应的时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出货数量" prop="shipmentQuantity">
              <el-input v-model="form.shipmentQuantity" placeholder="请输入出货数量" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="未代品数" prop="unsubstitutedQuantity">
              <el-input v-model="form.unsubstitutedQuantity" placeholder="请输入未代品数量" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="6">
          </el-col>
          <el-col :span="6">
          </el-col>
          <el-col :span="6">
          </el-col>
        </el-row>


<!--        <el-form-item label="项目id" prop="projectId">-->
<!--          <el-input v-model="form.projectId" placeholder="请输入项目id" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="产品id" prop="productId">-->
<!--          <el-input v-model="form.productId" placeholder="请输入产品id" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="项目产品ID" prop="projectProductId">-->
<!--          <el-input v-model="form.projectProductId" placeholder="请输入项目产品ID" />-->
<!--        </el-form-item>-->


<!--        <el-form-item label="返品数量对应的时间" prop="returnQuantityTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.returnQuantityTime"-->
<!--            type="date"-->
<!--            value-format="YYYY-MM-DD"-->
<!--            placeholder="请选择返品数量对应的时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="返品数量" prop="returnQuantity">-->
<!--          <el-input v-model="form.returnQuantity" placeholder="请输入返品数量" />-->
<!--        </el-form-item>-->

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ScmDefectInfo">
import { listScmDefectInfo, getScmDefectInfo, delScmDefectInfo, addScmDefectInfo, updateScmDefectInfo } from "@/api/scm/scmDefectInfo";
import {listScmProjectProducts} from "@/api/scm/scmProjectProducts.js";
import {listScmCustomerOrders} from "@/api/scm/scmCustomerOrders.js";

const { proxy } = getCurrentInstance();
const { scm_defect_status } = proxy.useDict('scm_defect_status');

const scmDefectInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: null,
    productId: null,
    projectProductId: null,
    customerOrderId: null,
    orderCode: null,
    defectDate: null,
    status: null,
    inspectionCount: null,
    defectCount: null,
    defectRate: null,
    defectType: null,
    defectDetails: null,
    reasonAnalysis: null,
    countermeasure: null,
    toCustReturnDate: null,
    returnQuantityTime: null,
    returnQuantity: null,
    shipmentQuantityTime: null,
    shipmentQuantity: null,
    unsubstitutedQuantity: null,
  },
  rules: {
    customerOrderId: [
      { required: true, message: "订单ID不能为空", trigger: "blur" }
    ],
    orderCode: [
      { required: true, message: "订单编号不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询不良品信息记录列表 */
function getList() {
  loading.value = true;
  listScmDefectInfo(queryParams.value).then(response => {
    scmDefectInfoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectId: null,
    productId: null,
    projectProductId: null,
    customerOrderId: null,
    orderCode: null,
    defectDate: null,
    status: null,
    inspectionCount: null,
    defectCount: null,
    defectRate: null,
    defectType: null,
    defectDetails: null,
    reasonAnalysis: null,
    countermeasure: null,
    toCustReturnDate: null,
    returnQuantityTime: null,
    returnQuantity: null,
    shipmentQuantityTime: null,
    shipmentQuantity: null,
    unsubstitutedQuantity: null,
    projectProduct: {
      id: null,
      projectId: null,
      productId: null,
      projectProductStatus: null,
      customerStatus: null,
      supplierStatus: null,
      purchaseCategory: null,
      demandType: null,
      drawingNuber: null,
      version: null,
      internalVersion: null,
      productName:  null,
      material: null,
      inflamingRetardingLevel:  null,
      specification: null,
      model: null,
      color: null,
      drawingComposition: null,
      remark: null
    },
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("scmDefectInfoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加不良品信息记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getScmDefectInfo(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改不良品信息记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["scmDefectInfoRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateScmDefectInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addScmDefectInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除不良品信息记录编号为"' + _ids + '"的数据项？').then(function() {
    return delScmDefectInfo(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('scm/scmDefectInfo/export', {
    ...queryParams.value
  }, `scmDefectInfo_${new Date().getTime()}.xlsx`)
}

getList();

// 产品 图号 客户下拉框
const optionsOfProduct = ref([]);
const projectProductsList = ref([]);
const queryParamsOfProjectProducts = ref({});

function resetQueryOfProjectProducts() {
  queryParamsOfProjectProducts.value = {
    pageNum: 1,
    pageSize: 100,
    projectId: null,
    projectProductsNo: null,
    drawingNumber: null,
  }
}
function remoteMethodOfProjectProducts(query) {
  console.log('query', query);
  resetQueryOfProjectProducts();
  if (query !== ''){
    queryParamsOfProjectProducts.value.drawingNumber = query.trim();
    listProjectProductsSelect();
  }
}
function initializeProjectProductsOptions(projectProductsId) {
  console.log('projectProductsId', projectProductsId)
  resetQueryOfProjectProducts();
  queryParamsOfProjectProducts.value.id = projectProductsId;
  listProjectProductsSelect();
  // queryParamsOfProjectProductsContacts.value.projectProductsId = projectProductsId;
  // listProjectProductsContactsSelect();
}
function handleChangeOfProjectProducts(value) {
  console.log('value', value);
  // form.value.projectProductsId = value;
  const projectProducts = projectProductsList.value.find(projectProducts => projectProducts.id === value);
  form.value.projectProduct.productName = projectProducts.productName;
  form.value.projectProduct.version = projectProducts.version;
  form.value.projectProduct.internalVersion = projectProducts.internalVersion;
  // form.value.projectProductsContactId = 0;
  // form.value.projectProductsContactName = " ";
}
function listProjectProductsSelect() {
  listScmProjectProducts(queryParamsOfProjectProducts.value).then(response => {
    projectProductsList.value = response.rows;
    optionsOfProduct.value = projectProductsList.value.map(projectProducts => ({
      label: projectProducts.drawingNumber,
      value: projectProducts.id,
    }));
  });
}

// 订单下拉框
const optionsOfCustomerOrders = ref([]);
const customerOrdersList = ref([]);
const queryParamsOfCustomerOrders = ref({});

function resetQueryOfCustomerOrders() {
  queryParamsOfCustomerOrders.value = {
    pageNum: 1,
    pageSize: 100,
    projectId: null,
    projectProductsNo: null,
    drawingNumber: null,
  }
}
function remoteMethodOfCustomerOrders(query) {
  console.log('query', query);
  resetQueryOfCustomerOrders();
  if (query !== ''){
    // queryParamsOfCustomerOrders.value.drawingNumber = query.trim();
    listCustomerOrdersSelect();
  }
}
function initializeCustomerOrdersOptions(projectProductsId) {
  console.log('projectProductsId', projectProductsId)
  resetQueryOfCustomerOrders();
  // queryParamsOfProjectProducts.value.id = projectProductsId;
  listCustomerOrdersSelect();
  // queryParamsOfProjectProductsContacts.value.projectProductsId = projectProductsId;
  // listProjectProductsContactsSelect();
}
function handleChangeOfCustomerOrders(value) {
  console.log('value', value);
  // form.value.projectProductsId = value;
  // const projectProducts = projectProductsList.value.find(projectProducts => projectProducts.id === value);
  // form.value.projectProduct.productName = projectProducts.productName;
  // form.value.projectProduct.version = projectProducts.version;
  // form.value.projectProduct.internalVersion = projectProducts.internalVersion;
  // form.value.projectProductsContactId = 0;
  form.value.orderCode = customerOrdersList.value.find(customerOrder => customerOrder.id === value).orderCode;
}
function listCustomerOrdersSelect() {
  listScmCustomerOrders(queryParamsOfProjectProducts.value).then(response => {
    customerOrdersList.value = response.rows;
    optionsOfCustomerOrders.value = customerOrdersList.value.map(customerOrder => ({
      label: customerOrder.orderCode,
      value: customerOrder.id,
    }));
  });
}

// 列显隐信息
const columns = ref([
  { key: 0, label: `版本`, visible: true },
  { key: 1, label: `内版本`, visible: true },
  { key: 2, label: `品名`, visible: true },
  { key: 3, label: `材质`, visible: true },
  { key: 4, label: `规格`, visible: true },
  { key: 5, label: `颜色`, visible: true },
  { key: 6, label: `单台 用量`, visible: true },
  { key: 7, label: `月度 用量`, visible: true },
  { key: 8, label: `年度 用量`, visible: true },
  { key: 9, label: `一次性`, visible: true },
  { key: 10, label: `一次性试做`, visible: true },
  { key: 11, label: `试做`, visible: true },
  { key: 12, label: `量产`, visible: true },
  { key: 13, label: `希望报价日`, visible: true },
  { key: 14, label: `希望到货日`, visible: true },
  { key: 15, label: `需求资料`, visible: true },
  { key: 16, label: `备注`, visible: true }
]);

</script>
